package cn.mvcjava.dao;

import java.sql.Connection;
import java.util.List;

import cn.mvcjava.model.User;

public class UserDaoImp extends BaseDao<User> implements UserDao {

	@Override
	public int save(User user) {
	      String sql ="INSERT INTO `User` (`username`,`password`,`adress`,`phone`) VALUES(?,?,?,?);";
	      return super.update(sql, user.getUsername(),user.getPassword(),user.getAdress(),user.getPhone());
	}

	@Override
	public int deletectUserById(int id) {
		   String sql ="DELETE FROM `User` WHERE `id` = ?";
		 return super.update(sql, id);
	}

	@Override
	public int UpdateUserById(User user) {
		   String sql ="UPDATE `User` SET `username`= ? ,`password` =? ,`phone`=?,`adress`=? WHERE `id`=?";
	  return super.update(sql, user.getUsername(),user.getPassword(),user.getPhone(),user.getAdress(),user.getId());
	}
 
//	不支持事物
	@Override
	public User get(int id) {
		 String sql ="SELECT `id`,`username`,`password`,`phone`,`adress`, `reg_date` regDate FROM `User` where `id`=?";
		 return super.get(sql,id); 
	}

//支持事物。
	@Override
	public User get(Connection con, int id) {
		String sql ="SELECT `id`,`username`,`password`,`phone`,`adress`, `reg_date` regDate FROM `User` where `id`=?";
		 return super.get(con,sql,id); 
	}
	
	
	
	@Override
	public List<User> getListAll() {
		   String sql ="SELECT `username`,`password`,`phone`,`adress`,`reg_date` regDate FROM `User`";
	     return super.getList(sql);
	}

	@Override
	public long getCountName(String username) {
		   String sql ="SELECT  COUNT(`id`) FROM `User` where `username` =?";
		  return (long) super.getValue(sql, username);
	}

	@Override
	public List<User> query(String username, String adress, String phone) {
		String sql="SELECT `id`,`username`,`password`,`phone`,`adress`, `reg_date` regDate FROM `User` where 1=1";
		if(username!=null && !"".equals(username)) {
			sql = sql +" AND username like '%"+username+"%' ";  // 存在有sql 注入攻击的风险。
		}
		
		if(adress!=null && !"".equals(adress)) {
			sql = sql +" AND adress like '%"+adress+"%' ";
		}
		
		if(phone!=null && !"".equals(phone)) {
			sql = sql +" AND phone like '%"+phone+"%' ";
		}
		
		System.out.println(sql);
		return super.getList(sql);
	}



}
